package com.red.springmanual.service;

import com.red.springmanual.spring.BeanPostProcessor;
import com.red.springmanual.spring.Component;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object beforeInit(String beanName, Object bean) {
        if (beanName.equalsIgnoreCase("userService")) {
            System.out.println(beanName+"初始化前");

        }

        return bean;

    }

    @Override
    public Object afterInit(String beanName, Object bean) {
        if (beanName.equalsIgnoreCase("userService")) {
            System.out.println(beanName+"初始化后");

            Object proxyInstance = Proxy.newProxyInstance(MyBeanPostProcessor.class.getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                    System.out.println("前->切面逻辑");
                    Object invoke = method.invoke(bean, args);
                    System.out.println("后->切面逻辑");

                    return invoke;
                }
            });

            return proxyInstance;

        }



        return bean;

    }
}
